package com.databus;

import java.nio.ByteBuffer;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.databus.*;
import com.packet.PackageData;
import com.thread.TimeOutThread;

public class MultiPageManager implements TimeOutCallBack
{

	Map<Integer, LinkedList<PackageData>> pages;
	
	TimeOutThread timeout;
	
	public MultiPageManager(TimeOutThread timeout)
	{
		this.timeout = timeout;
		this.pages = new ConcurrentHashMap<Integer, LinkedList<PackageData>>();
	}

	/**
	 * 鍒ゆ柇鏄惁闇�瑕佹坊鍔爉ulti鍖咃紝濡傛灉涓嶆槸鐩存帴杩斿洖,濡傛灉鏄痬ulti,鏈�鍚庝竴涓寘灏辩粍鍖呭苟杩斿洖,涓嶆槸鏈�鍚庝竴涓寘灏辫繑鍥瀗ull
	 * 
	 * @param data
	 * @return
	 */
	public PackageData addPackageData(PackageData data) 
	{
		if (data.mHeader.isMulti())
		{
			int serilNum = data.mHeader.serialnum;
			LinkedList<PackageData> datas = pages.get(serilNum);
			if (datas == null && data.mHeader.getMultiPageNo() == 1) 
			{
				datas = new LinkedList<PackageData>();
				pages.put(serilNum, datas);
			}
				
			if(datas == null) 
			{
				//瓒呮椂琚竻闄ゅ垯鐩存帴涓㈡帀鏁版嵁
				return null;
			}
			datas.add(data);
			if (data.mHeader.getMultiPageNo() != 0) 
			{
				//reset timeout
				timeout.resetAddTimeout(serilNum);
				return null;
			}
			else
			{
				datas = pages.remove(serilNum);
				int size = getSize(datas);
				data.mData = getData(datas, size);
				return data;
			}
		}
		return data;
	}
	
	private int getSize(List<PackageData> datas)
	{
		int size = 0;
		for(PackageData data : datas) {
			size += data.mData.length;
		}
		return size;
	}
	
	private byte[] getData(List<PackageData> datas, int size) 
	{
		ByteBuffer buf = ByteBuffer.allocate(size);
		for(PackageData data : datas) {
			buf.put(data.mData);
		}
		return buf.array();
	}

	@Override
	public void OnMessageTimeOut(int serNum)
	{
		Log.debug("multi page clear serNum:"+serNum);
		pages.remove(serNum);
	}
}
